<template>
  <div id="knowledgegraph"></div>
</template>

<script>
export default {
  name: "KnowledgeGraph",
  props: {//props列表
    knowledge: [],
    speciality: []
  },
  data() {
    return {
      nodes: [//des应该是鼠标上移动的时候显示的tip
      ],
      links: [
        // {source: 'node01', target: 'node02', name: 'link01', des: 'link01des'},
        // {source: 'node01', target: 'node03', name: 'link02', des: 'link02des'},
        // {source: 'node01', target: 'node04', name: 'link03', des: 'link03des'},
        // {source: 'node01', target: 'node05', name: 'link04', des: 'link05des'},
        // {source: 'node06', target: 'node04', name: 'linkcat2', des: 'linkcat2'}
      ]
    }
  },
  methods: {
    loadgraph() {
      let myChart = this.$echarts.init(document.getElementById('knowledgegraph'));
      let categories = [{"name": "食物"}, {"name": "食谱"}, {"name": "食验疗方"}, {"name": "养生功效"}, {"name": "营养与功效"}]
      let option = {
        // 图的标题
        title: {
          text: '知识图谱'
        },
        // 提示框的配置
        tooltip: {
          formatter: function (x) {
            return x.data.des;
          }
        },
        // 工具箱
        toolbox: {
          // 显示工具箱
          show: true,
          feature: {
            mark: {
              show: true
            },
            // 还原
            restore: {
              show: true
            },
            // 保存为图片
            saveAsImage: {
              show: true
            }
          }
        },
        legend: [{//对图例组件的相关配置
          // selectedMode: 'single',
          top: "5%",
          testStyle: {
            fontSize: 20
          },
          data: categories.map(function (a) {
            return a.name;
          })
        }],
        series: [{
          type: 'graph', // 类型:关系图
          layout: 'force', //图的布局，类型为力导图
          symbolSize: 40, // 调整节点的大小
          roam: true, // 是否开启鼠标缩放和平移漫游。默认不开启。如果只想要开启缩放或者平移,可以设置成 'scale' 或者 'move'。设置成 true 为都开启
          edgeSymbol: ['circle', 'arrow'],//关系边两端的标记类型，可以是一个数组分别指定两端，也可以是单个统一指定。默认不显示标记，常见的可以设置为箭头
          edgeSymbolSize: [2, 10],//关系边两端的标记大小
          edgeLabel: {//关系边的属性设置
            normal: {
              textStyle: {
                fontSize: 10
              }
            }
          },
          symbol: "circle",
          force: {
            repulsion: 2200,//节点之间的斥力因子
            edgeLength: [15, 25]//边的两个节点之间的距离，这个距离也会受 repulsion
          },
          draggable: true,//节点是否可拖拽
          lineStyle: {//关系边的公用线条样式
            normal: {
              width: 3,//宽度
              color: '#4b565b',//颜色
            }
          },
          emphasis: {
            shadowColor: "rgba(0,255,222,0.49)",
            shadowOffsetX: 0,
            shadowOffsetY: 0,
            shadowBlur: 40,
          },
          label: {
            normal: {
              show: true,
              textStyle: {
                fontSize: 10
              },
              formatter: function (value) {
                let showtext = value.data.name
                if (showtext.length > 4) {
                  return `${showtext.slice(0, 4)}...`;
                }
                return showtext;
              }
            }
          },
          // 数据
          data: this.nodes,
          //source源节点 target目标节点 name 关系边名
          links: this.links,
          categories: categories,
          animationEasingUpdate: "quinticInOut",
        }],
      }
      myChart.setOption(option)
    },
    // 获取icon的图片信息
    getImgData(imgSrc) {
      let fun = function (resolve) {
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');
        const img = new Image();

        img.crossOrigin = '';
        img.onload = function () {
          let diameter = img.width;
          canvas.width = diameter;
          canvas.height = diameter;
          context.clearRect(0, 0, diameter, diameter);
          context.save();

          context.beginPath();
          context.arc(diameter / 2, diameter / 2, diameter / 2, 0, 2 * Math.PI);
          context.clip();

          context.drawImage(img, 0, 0, diameter, diameter); // 绘制图像
          context.restore();

          resolve(canvas.toDataURL('image/png'));
        };
        img.src = imgSrc;
      };
      return new Promise(fun);
    },
    preprocess() {
      //存放节点信息
      let dict = {}//定义一个字典
      dict['name'] = this.knowledge[0]['a']['name']
      dict['des'] = this.knowledge[0]['a']['name']
      dict['symbolSize'] = 90
      dict['category'] = 0
      this.nodes.push(dict)
      for (let j = 0; j < this.speciality.length; j++) {
        // eslint-disable-next-line vue/no-mutating-props
        this.speciality[j] = this.speciality[j].replace("_", "\n");
      }
      console.log(this.knowledge)
      for (let j = 0; j < this.speciality.length; j++) {
        console.log(this.speciality[j] + ":" + this.knowledge[j]['b']['name'])
        let dictnew = {}//定义一个字典
        dictnew['name'] = this.knowledge[j]['b']['name']
        dictnew['des'] = this.knowledge[j]['b']['name']
        dictnew['symbolSize'] = 80
        if (this.speciality[j] === 'IMG') {
          dictnew['category'] = 3
          dictnew['symbol'] = 'circle'
        } else if (this.speciality[j] === '食谱') {
          dictnew['category'] = 1
        } else if (this.speciality[j] === 'FOOD') {
          dictnew['category'] = 1
        } else if (this.speciality[j] === 'TCM') {
          dictnew['category'] = 2
        } else if (this.speciality[j] === '功效') {
          dictnew['category'] = 3
        } else if (this.speciality[j] === '功能主治') {
          dictnew['category'] = 4
        }
        if (j === 0) {
          let data = this.knowledge[j]['b']['name']
          console.log(data)
          this.getImgData(data)
              .then((res) => {
                console.log(res)
                dictnew['symbol'] = 'image://' + res
                // 在获取到图片数据后，再执行 loadgraph 方法进行图表加载和绘制
                this.loadgraph();
              })
              .catch((error) => {
                console.error('Failed to get image data:', error);
                // 在出现错误时，也可以尝试执行 loadgraph 方法进行图表加载和绘制
                this.loadgraph();
              });
        }
        this.nodes.push(dictnew)
      }
      //存放关系边信息
      for (let j = 0; j < this.speciality.length; j++) {
        let edgenew = {}//定义一个字典
        edgenew['source'] = this.knowledge[0]['a']['name']
        edgenew['target'] = this.knowledge[j]['b']['name']
        edgenew['name'] = this.speciality[j]
        edgenew['des'] = this.speciality[j]
        let showtext = {}
        showtext['show'] = true
        showtext['formatter'] = this.speciality[j]
        edgenew['label'] = showtext
        this.links.push(edgenew)
      }
    }
  },
  created() {
    this.$nextTick(function () {
      this.preprocess()
      this.loadgraph();
    });
  },
  //画布
}
</script>

<style scoped>
#knowledgegraph {
  width: 100%;
  height: 1000px;
  margin: auto;
  /*border: 1px solid #8080ff;*/
}
</style>
